use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

fn main() {
    // 获取项目根目录
    let project_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let target_dir = PathBuf::from(env::var("OUT_DIR").unwrap()).parent().unwrap().parent().unwrap().parent().unwrap();

    // 生成版本信息
    let mut version_info = String::new();

    // 1. 基础版本
    let base_version = env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.1.0".to_string());
    version_info.push_str(&format!("version=\"{}\"\n", base_version));

    // 2. Git commit hash (如果存在)
    let git_commit = Command::new("git")
        .args(&["rev-parse", "--short", "HEAD"])
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "unknown".to_string());

    version_info.push_str(&format!("git_commit=\"{}\"\n", git_commit));

    // 3. 构建时间 (使用 YYYYMMDD.HH 格式)
    let build_time = {
        let output = Command::new("date")
            .args(&["+%Y%m%d.%H"])
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
            .unwrap_or_else(|| "unknown".to_string());
        output
    };
    version_info.push_str(&format!("build_time=\"{}\"\n", build_time));

    // 4. 完整版本字符串
    let full_version = if git_commit != "unknown" {
        format!("{}+{}-{}", base_version, build_time, git_commit)
    } else {
        format!("{}+{}", base_version, build_time)
    };
    version_info.push_str(&format!("full_version=\"{}\"\n", full_version));

    // 5. 是否为脏工作区
    let dirty = Command::new("git")
        .args(&["status", "--porcelain"])
        .output()
        .ok()
        .map(|output| {
            output.status.success() && !String::from_utf8_lossy(&output.stdout).trim().is_empty()
        })
        .unwrap_or(false);
    version_info.push_str(&format!("dirty={}\n", dirty));

    // 写入版本文件
    let version_file = project_root.join("src").join("version.rs");

    // 生成详细的时间信息
    let detailed_time = Command::new("date")
        .args(&["+\"%Y-%m-%d %H:%M:%S UTC\""])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    let version_content = format!(
        "// AUTO-GENERATED FILE - DO NOT EDIT\n\
         // This file is generated by build.rs\n\
         \n\
         use std::borrow::Cow;\n\n\
         pub const VERSION: &str = \"{}\";\n\
         pub const BUILD_TIME: &str = \"{}\";\n\
         pub const BUILD_DATE: &str = \"{}\";\n\
         pub const GIT_COMMIT: &str = \"{}\";\n\
         pub const FULL_VERSION: &str = \"{}\";\n\
         pub const IS_DIRTY: bool = {};\n\n\
         pub fn get_version_display() -> Cow<'static, str> {{\n\
             Cow::Borrowed(FULL_VERSION)\n\
         }}\n\
         \n\
         pub fn is_clean() -> bool {{\n\
             !IS_DIRTY\n\
         }}\n\
         \n\
         pub fn get_build_info() -> String {{\n\
             let commit_display = if GIT_COMMIT.len() > 7 {{\n\
                 format!(\"@{}\", &GIT_COMMIT[..7])\n\
             }} else {{\n\
                 String::new()\n\
             }};\n\
             format!(\"v{} (built: {}{})\", VERSION, BUILD_DATE, commit_display)\n\
         }}\n",
        base_version,
        build_time,
        detailed_time,
        git_commit,
        full_version,
        dirty
    );

    fs::write(&version_file, version_content).unwrap();

    println!("cargo:rerun-if-changed=.git/HEAD");
    println!("cargo:rerun-if-changed=.git/refs");
    println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");
    println!("cargo:warning=Generated version info: {}", full_version);
}